package com.hluobo.library.action;

import javax.annotation.Resource;

import org.json.JSONObject;

import com.hluobo.library.model.User;
import com.hluobo.library.service.UserService;
import com.hluobo.library.util.StreamTool;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

	private UserService us;
	private int id;
	private User user;
	private int resCode = -1;
	private String msg = "err";

	/**
	 * 用户信息查询
	 * resCode 200查询成功 404用户不存在 
	 * @return
	 */
	public String query() {
		try {
			JSONObject jsonObj = StreamTool.readRequstString();
			int mId = jsonObj.getInt("id");
			user = us.query(User.class, mId);
			if(user != null){
				resCode = 200;
				msg = "查询成功";
			}else{
				resCode = 404;
				msg = "用户未找到";
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return "success";
	}

	/**
	 * 用户登录验证
	 * 传入数据为json字符串
	 * @return
	 */
	public String login() {

		try {
			JSONObject jsonObj = StreamTool.readRequstString();

			String username = jsonObj.getString("username");
			String password = jsonObj.getString("password");

			user = us.login(username, password);
			if (user != null) {
				resCode = 200;
				msg = "登陆成功";
			} else {
				resCode = 250;
				msg = "用户名或密码错误";
			}
		} catch (Throwable e) {
			resCode = 500;
			msg = "服务器端错误";
			e.printStackTrace();
		}

		return "success";
	}
	
	/**
	 * 用户修改
	 * @return
	 */
	public String update(){
		try {
			JSONObject jsonObject = StreamTool.readRequstString();
			boolean flag =  us.saveUserInfo(jsonObject);
			if(flag){
				resCode = 200;
				msg = "修改成功";
			}else{
				resCode = 250;
				msg = "修改失败";
			}
		} catch (Throwable e) {
			resCode = 500;
			msg = "服务器端错误";
			e.printStackTrace();
		}
		
		
		return "success";
	}

	@Resource(name = "userService")
	public void setUs(UserService us) {
		this.us = us;
	}

	public void setId(int id) {
		this.id = id;
	}

	public User getUser() {
		return user;
	}

	public int getResCode() {
		return resCode;
	}

	public String getMsg() {
		return msg;
	}

}
